package com.core.springSecurity.handle;

import com.common.ErrorCodeEnum;
import com.common.utils.NetworkUtils;
import com.common.utils.ServletUtils;
import com.common.utils.Utils;
import com.core.springSecurity.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 创建token对应的LoginUserDetails失败时会进入这里
 *
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Resource
    private TokenService tokenService;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        String mes = e.getMessage();
        final String ip = NetworkUtils.getIPAddress(request);
        log.debug("身份认证失败 requestIp:{} path:{}", ip,request.getServletPath());
        ServletUtils.renderString(response, Utils.result(ErrorCodeEnum.UNAUTHORIZED).toJSONString());
    }
}
